onload = () => {
    loadCSS("../css/fontello.css", "bootstrap5-icon");
    loadCSS("../css/bootstrap5.min.css", "bootstrap5");
    loadCSS("../css/common.css", "common");
    loadScript("../js/bootstrap5.bundle.min.js")
        .then(() => loadScript("../js/crud.js")).then(() => {
        let arOperator = new Crud({
            module: "arDetail",
            hasCheckbox: true,
            iterators: [
                {
                    name: "ar.customer", type: "arCustomer", convert: u => {
                        return {value: u, "caption": u}
                    }
                }
            ],
            extendAttribute: [{name: "arDetailId", type: "arCharge"},
                {name: "trackingNo", type: "apChargeByTrackingNo"},
                {name: "updatedBy", type: "userById"}],
            opsButton: ["delete", {
                "caption": "Delete By BillNo",
                "class": "btn btn-primary",
                "callback": () => {
                    let billNo = prompt("Please input bill# to be deleted.");
                    if (billNo)
                        return ajax("/ar/deleteByBill?billNo=" + billNo, {method: "GET"}, data => {
                            showToast(`Delete successful: ${JSON.stringify(data.data)}`, "primary");
                            loadData();
                        }, error => showToast(`ERROR: description: ${error}`));
                }
            }, {
                "caption": "Upload GPS Excel/CSV",
                "class": "btn btn-primary",
                hint: "Add GPS file",
                "action": "modal",
                "param": "#uploadQuoteFile",
                "commit": (form, e) => {
                    const fileInput = form.querySelector('#formFile');
                    const formData = new FormData();
                    formData.append('file', fileInput.files[0]);
                    const url = (fileInput.files[0].name.endsWith(".csv")) ? "/ar/csv" : "/ar/excel";
                    return ajax(url, {method: "POST", body: formData, headers: {}}, data => {
                        showToast(`Upload successful: ${JSON.stringify(data.data)}`, "primary");
                        loadData();
                        let modalElement = document.getElementById("uploadQuoteFile");
                        const modal = bootstrap.Modal.getInstance(modalElement)
                            || new bootstrap.Modal(modalElement);
                        modal.hide();
                    }, error => showToast(`ERROR: description: ${error}`));
                }
            }],
            rowBtn: ["delete"],
            search: [
                {"caption": "Bill #", "type": "text", "name": "billNo", class: "col-3"},
                {"caption": "Tracking #", "type": "text", "name": "trackingNo", class: "col-3"},
                {"caption": "Customer", "type": "combo", "name": "customer",iterator:"blank_ALL_ar.customer", class: "col-3"},
                {"caption": "From", "type": "date", "name": "fromDate", class: "col-3"},
                {"caption": "To", "type": "date", "name": "toDate", class: "col-3"},
            ],
            listField: [{"caption": "ID", "field": "arDetailId"},
                {caption: "Tracking#", "field": "trackingNo"},
                {caption: "Customer", "field": "customer"},
                {
                    caption: "Earliest Bill Date",
                    "field": "billingTime",
                    format: str => subString(str,0,10)
                },
                {caption: "Create Time", "field": "initTime", format: str => subString(str,0,10)},
                {caption: "Biz. Time", "field": "bizTime", format: str => subString(str,0,10)},
                {caption: "Fee", "field": "fee", format: v => v / 100},
                {caption: "Currency", "field": "currency"},
                {caption: "Weight", "field": "weight"},
                {caption: "UpdateTime", "field": "createTime", format: str => subString(str,0,10)},
                {caption: "UpdatedBy", "field": "updatedBy_userById.userName"}],
            rowEvent: function (e, item, tr, outer) {
                outer.subTable["chargeTable"].load(item["arDetailId_arCharge"]);
                outer.subTable["chargeTable2"].load(item["trackingNo_apChargeByTrackingNo"]);
                canvas.show();
            },
            subTable: [{
                name: "chargeTable",
                tableId: "chargeTable",
                listField: [{"caption": "Bill#", "field": "billNo"},
                    {"caption": "Charge Code", "field": "chargeCode"},
                    {"caption": "Bill Time", "field": "billingTime", format: str => subString(str,0,10)},
                    {"caption": "Fee", "field": "fee", format: str => str / 100},
                    {"caption": "Currency", "field": "currency"},
                    {"caption": "AR ID", "field": "arStatementId"},
                    {"caption": "AP ID", "field": "apStatementId"}
                ],
                stat: stat
            }, {
                name: "chargeTable2",
                tableId: "chargeTable2",
                listField: [{"caption": "Bill#", "field": "billNo"},
                    {"caption": "Charge Code", "field": "chargeCode"},
                    {"caption": "Bill Time", "field": "billingTime", format: str => subString(str,0,10)},
                    {"caption": "Fee", "field": "fee", format: str => str / 100},
                    {"caption": "Currency", "field": "currency"},
                    {"caption": "AR ID", "field": "arStatementId"},
                    {"caption": "AP ID", "field": "apStatementId"}
                ],
                stat: stat
            }],
            editFields: [
                {"name": "code", "placeHolder": "code", "required": "required"},
                {"name": "pk", "placeHolder": "PK in cargo wise", "required": "required"},
                {caption: "Full Name:", "name": "fullname", "placeHolder": "Full name", "required": "required"}
            ]
        });
        arOperator.init();

        function loadData() {
            arOperator.loadData();
        }

        function stat() {
            const arTable = document.getElementById("chargeTable");
            const apTable = document.getElementById("chargeTable2");
            let rows = arTable.querySelector("tbody").querySelectorAll("tr");
            let revenue = 0;
            rows.forEach(row => {
                revenue += Number(row.querySelectorAll("td")[3]?.innerText)
            });
            rows = apTable.querySelector("tbody").querySelectorAll("tr");
            let cost = 0;
            rows.forEach(row => {
                cost += Number(row.querySelectorAll("td")[3]?.innerText)
            });
            document.getElementById("stat_revenue").innerHTML = revenue.toFixed(2);
            document.getElementById("stat_cost").innerHTML = cost.toFixed(2);
            document.getElementById("stat_profit").innerHTML = (revenue - cost).toFixed(2);
            if (revenue > cost) {
                document.getElementById("stat_profit").classList.remove("text-danger");
                document.getElementById("stat_profit").classList.add("text-primary");
            } else {
                document.getElementById("stat_profit").classList.remove("text-primary");
                document.getElementById("stat_profit").classList.add("text-danger");
            }
            document.getElementById("stat_margin").innerHTML = (100 * (revenue - cost) / revenue).toFixed(2);
        }

        const canvas = new bootstrap.Offcanvas(document.getElementById('subtable'));
    }).catch((err) => console.error(err));
}
